#include <Wire.h>
#include <RTClib.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// OLED 设置
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

// RTC
RTC_DS3231 rtc;

// 引脚定义
const int buttonH = 2;
const int buttonM = 3;
const int buttonOK = 4;
const int buzzerPin = 6;
const int statusLED = 7;
const int vibMotor = 5;
const int led1 = 10;
const int led2 = 11;
const int led3 = 12;

struct PillTime {
  int hour;
  int minute;
};

PillTime pillTimes[3] = {
  {8, 0},
  {12, 0},
  {20, 0}
};

int currentSetting = 0;
int settingStep = 0;
unsigned long lastSettingTime = 0;
bool inSettingMode = false;

// 检测按键按下（下降沿）
bool wasPressed(int pin) {
  static bool lastState[20] = {false};
  bool current = digitalRead(pin) == LOW;
  bool triggered = (current && !lastState[pin]);
  lastState[pin] = current;
  return triggered;
}

// 提醒处理
void triggerReminder(int ledPin) {
  unsigned long startTime = millis();

  digitalWrite(ledPin, HIGH);
  digitalWrite(buzzerPin, HIGH);
  digitalWrite(vibMotor, HIGH);

  displayMessage("Time to take pill!");

  // 循环检查是否有按钮按下，或超时
  while (millis() - startTime < 60000) {
    if (digitalRead(buttonOK) == LOW) {
      break; // 提前结束提醒
    }
    delay(100); // 稍作延迟减少 CPU 占用
  }

  digitalWrite(ledPin, LOW);
  digitalWrite(buzzerPin, LOW);
  digitalWrite(vibMotor, LOW);
}

// 时间显示
void displayTime(DateTime now) {
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.printf("%02d:%02d:%02d", now.hour(), now.minute(), now.second());
  display.setTextSize(1);
  display.setCursor(0, 40);
  display.printf("Pill 1: %02d:%02d", pillTimes[0].hour, pillTimes[0].minute);
  display.setCursor(0, 50);
  display.printf("Pill 2: %02d:%02d", pillTimes[1].hour, pillTimes[1].minute);
  display.setCursor(70, 50);
  display.printf("Pill 3: %02d:%02d", pillTimes[2].hour, pillTimes[2].minute);
  display.display();
}

// 设置时的提示界面
void displaySetting() {
  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.printf("Setting Pill %d", currentSetting + 1);

  if (settingStep == 0) {
    display.setCursor(0, 20);
    display.printf("Hour: %02d", pillTimes[currentSetting].hour);
  } else if (settingStep == 1) {
    display.setCursor(0, 20);
    display.printf("Minute: %02d", pillTimes[currentSetting].minute);
  } else {
    display.setCursor(0, 20);
    display.print("Press OK to next pill");
  }

  display.display();
}

// 显示短信息
void displayMessage(String msg) {
  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0, 20);
  display.println(msg);
  display.display();
}

// 更新设置状态
void updateSetting() {
  bool updated = false;

  if (wasPressed(buttonH)) {
    pillTimes[currentSetting].hour = (pillTimes[currentSetting].hour + 1) % 24;
    updated = true;
  }
  if (wasPressed(buttonM)) {
    pillTimes[currentSetting].minute = (pillTimes[currentSetting].minute + 1) % 60;
    updated = true;
  }
  if (wasPressed(buttonOK)) {
    settingStep++;
    if (settingStep > 2) {
      settingStep = 0;
      currentSetting = (currentSetting + 1) % 3;
    }
    updated = true;
  }

  if (updated) {
    lastSettingTime = millis();
    inSettingMode = true;
    displaySetting();
  }
}

void setup() {
  Wire.begin(8, 9);  // 替换为你的 SDA / SCL 引脚号
  pinMode(buttonH, INPUT_PULLUP);
  pinMode(buttonM, INPUT_PULLUP);
  pinMode(buttonOK, INPUT_PULLUP);
  pinMode(buzzerPin, OUTPUT);
  pinMode(statusLED, OUTPUT);
  pinMode(vibMotor, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

  rtc.begin();
  if (rtc.lostPower()) {
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  delay(500);
  display.clearDisplay();
}

void loop() {
  static unsigned long playPressedTime = 0;
  static bool playLongPressHandled = false;

  // 检测 PLAY 是否被按下（确认键）
  if (digitalRead(buttonOK) == LOW) {
    if (playPressedTime == 0) {
      playPressedTime = millis();  // 开始计时
    } else if (!playLongPressHandled && millis() - playPressedTime > 3000) {
      // 长按超过 3 秒：恢复默认
      pillTimes[0] = {8, 0};
      pillTimes[1] = {12, 0};
      pillTimes[2] = {20, 0};

      displayMessage("Reset to Default!");
      delay(1500);  // 显示提示信息
      playLongPressHandled = true;

      // 退出设置状态
      inSettingMode = false;
      settingStep = 0;
      currentSetting = 0;
    }
  } else {
    playPressedTime = 0;
    playLongPressHandled = false;
  }

  updateSetting();

  // 退出设置模式：超过5秒未操作
  if (inSettingMode && millis() - lastSettingTime > 5000) {
    inSettingMode = false;
    display.clearDisplay();
  }

  if (!inSettingMode) {
    DateTime now = rtc.now();
    displayTime(now);

    for (int i = 0; i < 3; i++) {
      if (now.hour() == pillTimes[i].hour && now.minute() == pillTimes[i].minute && now.second() == 0) {
        int ledPin = (i == 0) ? led1 : (i == 1) ? led2 : led3;
        triggerReminder(ledPin);
      }
    }
  }

  delay(500);
}